<template>
  <div class="users-container">
    <!-- 面包屑导航 -->
    <div class="header">
      <el-breadcrumb separator=">>">        
        <el-breadcrumb-item>系统管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>    
    <el-divider></el-divider>
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名：">
          <el-input 
            v-model="searchForm.username" 
            placeholder="请输入用户名" 
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-divider></el-divider>
    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleCreate" class="create-btn">添加用户</el-button>
      <el-button 
        type="danger" 
        @click="handleBatchDelete" 
        :disabled="selectedUsers.length === 0"
        class="batch-delete-btn">
        批量删除 ({{ selectedUsers.length }})
      </el-button>
    </div>
    
    <!-- 用户表格 -->
    <el-table 
      ref="tableRef"
      :data="users" 
      border 
      stripe 
      style="width: 100%" 
      v-loading="loading"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="username" label="用户名" width="120"></el-table-column>
      <el-table-column prop="name" label="姓名" width="120"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="role" label="角色" width="120"></el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
            {{ scope.row.status === 'active' ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 创建用户对话框 -->
    <el-dialog v-model="dialog.createVisible" title="创建用户" width="500px">
      <el-form 
        :model="createForm" 
        :rules="createRules" 
        ref="createRef" 
        label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="createForm.username" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="createForm.name" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="createForm.email" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="createForm.role" style="width: 100%">
            <el-option label="管理员" value="管理员" />
            <el-option label="普通用户" value="普通用户" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="createForm.status" style="width: 100%">
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialog.createVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCreate" :loading="dialog.createLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 编辑用户对话框 -->
    <el-dialog v-model="dialog.editVisible" title="编辑用户" width="500px">
      <el-form 
        :model="editForm" 
        :rules="editRules" 
        ref="editRef" 
        label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="editForm.role" style="width: 100%">
            <el-option label="管理员" value="管理员" />
            <el-option label="普通用户" value="普通用户" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" style="width: 100%">
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialog.editVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit" :loading="dialog.editLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getUsers, createUser, updateUser, deleteUser } from '@/services/userService'

export default {
  name: 'Users',
  data() {
    return {
      users: [],
      loading: false,
      selectedUsers: [], // 新增：用于存储选中的用户
      // 搜索表单
      searchForm: {
        username: ''
      },
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      dialog: {
        createVisible: false,
        createLoading: false,
        editVisible: false,
        editLoading: false
      },
      createForm: {
        username: '',
        name: '',
        email: '',
        role: '普通用户',
        status: 'active'
      },
      editForm: {
        id: null,
        username: '',
        name: '',
        email: '',
        role: '普通用户',
        status: 'active'
      },
      createRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      },
      editRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.fetchUsers()
  },
  methods: {
    async fetchUsers() {
      this.loading = true
      try {
        const response = await getUsers(this.pagination.currentPage, this.pagination.pageSize, this.searchForm.username)
        if (response.code === 200) {
          this.users = response.data.users
          this.pagination.total = response.data.total
        } else {
          this.$message.error(response.message || '获取用户列表失败')
        }
      } catch (error) {
        this.$message.error('获取用户列表失败: ' + error.message)
      } finally {
        this.loading = false
      }
    },
    
    handleSearch() {
      // 重置到第一页并重新获取数据
      this.pagination.currentPage = 1
      this.fetchUsers()
    },
    
    handleReset() {
      // 重置搜索表单并重新获取数据
      this.searchForm.username = ''
      this.pagination.currentPage = 1
      this.fetchUsers()
    },
    
    handleCreate() {
      this.dialog.createVisible = true
      this.$nextTick(() => {
        this.$refs.createRef.resetFields()
      })
    },
    
    async submitCreate() {
      this.$refs.createRef.validate(async (valid) => {
        if (valid) {
          this.dialog.createLoading = true
          try {
            const response = await createUser(this.createForm)
            if (response.code === 200) {
              this.$message.success('用户创建成功')
              this.dialog.createVisible = false
              this.fetchUsers()
            } else {
              this.$message.error(response.message || '创建用户失败')
            }
          } catch (error) {
            this.$message.error('创建用户失败: ' + error.message)
          } finally {
            this.dialog.createLoading = false
          }
        }
      })
    },
    
    handleEdit(row) {
      this.editForm = { ...row }
      this.dialog.editVisible = true
      this.$nextTick(() => {
        this.$refs.editRef.clearValidate()
      })
    },
    
    async submitEdit() {
      this.$refs.editRef.validate(async (valid) => {
        if (valid) {
          this.dialog.editLoading = true
          try {
            const response = await updateUser(this.editForm.id, this.editForm)
            if (response.code === 200) {
              this.$message.success('用户更新成功')
              this.dialog.editVisible = false
              this.fetchUsers()
            } else {
              this.$message.error(response.message || '更新用户失败')
            }
          } catch (error) {
            this.$message.error('更新用户失败: ' + error.message)
          } finally {
            this.dialog.editLoading = false
          }
        }
      })
    },
    
    handleDelete(row) {
      this.$confirm(`确定要删除用户"${row.name}"吗？`, '删除用户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await deleteUser(row.id)
          if (response.code === 200) {
            this.$message.success('用户删除成功')
            this.fetchUsers()
          } else {
            this.$message.error(response.message || '删除用户失败')
          }
        } catch (error) {
          this.$message.error('删除用户失败: ' + error.message)
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchUsers()
    },
    
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.fetchUsers()
    },
    
    handleSelectionChange(selection) {
      this.selectedUsers = selection
    },
    
    async handleBatchDelete() {
      if (this.selectedUsers.length === 0) {
        this.$message.warning('请至少选择一个用户进行删除')
        return
      }
      
      try {
        await this.$confirm(
          `确定要删除选中的 ${this.selectedUsers.length} 个用户吗？`,
          '批量删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        const deletePromises = this.selectedUsers.map(user => deleteUser(user.id))
        const results = await Promise.allSettled(deletePromises)
        
        // 检查成功和失败的数量
        const successfulDeletes = results.filter(result => result.status === 'fulfilled').length
        const failedDeletes = results.filter(result => result.status === 'rejected').length
        
        if (failedDeletes > 0) {
          this.$message.error(`批量删除完成，成功删除 ${successfulDeletes} 个用户，失败 ${failedDeletes} 个`)
        } else {
          this.$message.success(`成功删除 ${successfulDeletes} 个用户`)
        }
        
        // 重新获取用户列表
        this.fetchUsers()
        // 清空选中项
        this.$nextTick(() => {
          if (this.$refs.tableRef) {
            this.$refs.tableRef.clearSelection()
          }
        })
      } catch (error) {
        // 用户取消删除操作
        if (error !== 'cancel') {
          this.$message.error('批量删除失败: ' + error.message)
        }
      }
    }
  }
}
</script>

<style scoped>
.users-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
}

.toolbar {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>